package org.apache.my;


import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class Test02 {


	public static void main(String[] args) throws ClassNotFoundException {

		System.out.println(Class.forName("com.mysql.jdbc.Driver").getClass());

		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/aab?characterEncoding=UTF-8&zeroDateTimeBehavior=round&useSSL=false";
		String username="root";
		String password="123456";
		//创建使用缓存池的数据源
		/*
		 * <dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}"/>
				<property name="url" value="${jdbc.url}"/>
				<property name="username" value="${jdbc.username}"/>
				<property name="password" value="${jdbc.password}"/>
			</dataSource>
		 */
		DataSource dataSource =new PooledDataSource(driver,url,username,password);

		//创建事务
		/*
		 * <transactionManager type="JDBC" />
		 */
		TransactionFactory transactionFactory =  new JdbcTransactionFactory();

		Environment environment = new Environment("development", transactionFactory, dataSource);

		Configuration configuration = new Configuration(environment);
		//加入资源
		/*
		 * <mapper resource="ssm/BlogMapper.xml"/>
		 */
		configuration.addMapper(UserMapper.class);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration);

		SqlSession sqlSession = sessionFactory.openSession();
	    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	    //第一次查询，发出sql语句，并将查询的结果放入缓存中
	    User u1 = userMapper.detail(1l);
	    System.out.println(u1);

	    //第二次查询，由于是同一个sqlSession,会在缓存中查找查询结果
	    //如果有，则直接从缓存中取出来，不和数据库进行交互
	    User u2 = userMapper.detail(1l);
	    System.out.println(u2);

	     userMapper.update(1l);

	    User u3 = userMapper.detail(1l);
	    System.out.println(u3);

	    sqlSession.close();
	}


}
